package org.jsola.hr.service.impl;

import org.jsola.core.Page;
import org.jsola.core.entity.BaseDO;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.IEmpCertificateDAO;
import org.jsola.hr.dto.EmpCertificateAddDTO;
import org.jsola.hr.dto.EmpCertificateDTO;
import org.jsola.hr.dto.EmpCertificateUpdateDTO;
import org.jsola.hr.entity.EmpCertificateDO;
import org.jsola.hr.query.EmpCertificateQuery;
import org.jsola.hr.service.IEmpCertificateService;
import org.jsola.hr.vo.EmpCertificateListVO;
import org.jsola.hr.vo.EmpCertificateVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhr
 */
@Service("hrEmpCertificateServiceImpl")
public class EmpCertificateServiceImpl implements IEmpCertificateService {

    @Autowired
    private IEmpCertificateDAO empCertificateDAO;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public EmpCertificateVO save(EmpCertificateAddDTO empCertificateAddDTO, TokenUser tokenUser) {
        // 转DO
        EmpCertificateDO empCertificateDO = empCertificateAddDTO.to(EmpCertificateDO.class);

        // 校验员工和公司
        checkEmpAndCompany(empCertificateDO.getEmpId(), empCertificateDO.getCompanyId(), tokenUser.getSiteId());

        // 保存
        empCertificateDO = save(empCertificateDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return empCertificateDO.to(EmpCertificateVO.class);
    }

    /**
     * 校验员工和公司
     *
     * @param empId     员工id
     * @param companyId 公司id
     * @param siteId    站点
     */
    private void checkEmpAndCompany(String empId, String companyId, String siteId) {
        ParamException.hasLength(empId, "员工id不能为空");
        ParamException.hasLength(companyId, "公司id不能为空");
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(EmpCertificateUpdateDTO empCertificateUpdateDTO, TokenUser tokenUser) {
        //转DO
        EmpCertificateDO empCertificateDO = empCertificateUpdateDTO.to(EmpCertificateDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(empCertificateDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... empCertificateIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) empCertificateIds);
    }


    @Override
    public EmpCertificateVO selectById(String empCertificateId, String siteId) {
        EmpCertificateDO empCertificateDO = selectDOById(empCertificateId, siteId);
        if (empCertificateDO == null) {
            return null;
        }
        return empCertificateDO.to(EmpCertificateVO.class);
    }

    @Override
    public List<EmpCertificateListVO> select(EmpCertificateQuery empCertificateQuery, String siteId) {
        List<EmpCertificateDO> empCertificateDOList = selectDO(empCertificateQuery, siteId);
        if(CollectionUtils.isEmpty(empCertificateDOList)) {
            return empCertificateDOList == null ? null : new ArrayList<>();
        }
        return empCertificateDOList.stream()
                .map(empCertificateDO -> empCertificateDO.to(EmpCertificateListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(EmpCertificateQuery empCertificateQuery, String siteId) {
        Example example = buildExample(empCertificateQuery,siteId);
        return empCertificateDAO.selectCountByExample(example);
    }

    @Override
    public Page<EmpCertificateListVO> selectPage(EmpCertificateQuery empCertificateQuery, String siteId) {
        Example example = buildExample(empCertificateQuery,siteId);
        Page<EmpCertificateDO> page = empCertificateDAO.selectPageByExample(example,
                empCertificateQuery.getPageNo(),
                empCertificateQuery.getPageSize());

        return page.to(EmpCertificateListVO.class);
    }

    @Override
    public EmpCertificateDO selectDOById(String empCertificateId, String siteId) {
        return listById(empCertificateId, siteId);
    }

    @Override
    public List<EmpCertificateDO> selectDO(EmpCertificateQuery empCertificateQuery, String siteId) {
        Example example = buildExample(empCertificateQuery,siteId);
        return empCertificateDAO.selectByExample(example);
    }


    /**
     * 根据查询参数，构建example

     * @param empCertificateQuery 查询参数
     * @param siteId 所属站点id
     * @return example
     */
    private Example buildExample(EmpCertificateQuery empCertificateQuery, String siteId) {
        Example example = new Example(EmpCertificateDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        if (empCertificateQuery.getEmpId() != null) {
            example.and().andLike("empId", "%" + empCertificateQuery.getEmpId() + "%");
        }
        if (empCertificateQuery.getType() != null) {
            example.and().andEqualTo("type", empCertificateQuery.getType());
        }
        if (empCertificateQuery.getName() != null) {
            example.and().andLike("name", "%" + empCertificateQuery.getName() + "%");
        }
        if (empCertificateQuery.getLevel() != null) {
            example.and().andEqualTo("level", empCertificateQuery.getLevel());
        }
        if (empCertificateQuery.getNumber() != null) {
            example.and().andLike("number", "%" + empCertificateQuery.getNumber() + "%");
        }
        if (empCertificateQuery.getStartTimeStart() != null &&
                empCertificateQuery.getStartTimeEnd() != null) {
            example.and().andBetween("startTime", empCertificateQuery.getStartTimeStart(),
                    empCertificateQuery.getStartTimeEnd());
        }
        if (empCertificateQuery.getEndTimeStart() != null &&
                empCertificateQuery.getEndTimeEnd() != null) {
            example.and().andBetween("endTime", empCertificateQuery.getEndTimeStart(),
                    empCertificateQuery.getEndTimeEnd());
        }
        if (empCertificateQuery.getRemark() != null) {
            example.and().andLike("remark", "%" + empCertificateQuery.getRemark() + "%");
        }
        if (empCertificateQuery.getCompanyId() != null) {
            example.and().andEqualTo("companyId", empCertificateQuery.getCompanyId());
        }
        if (empCertificateQuery.getGmtCreateStart() != null &&
                empCertificateQuery.getGmtCreateEnd() != null) {
            example.and().andBetween("gmtCreate", empCertificateQuery.getGmtCreateStart(),
                    empCertificateQuery.getGmtCreateEnd());
        }
        if (empCertificateQuery.getCreateUserId() != null) {
            example.and().andLike("createUserId", "%" + empCertificateQuery.getCreateUserId() + "%");
        }
        if (empCertificateQuery.getGmtModifiedStart() != null &&
                empCertificateQuery.getGmtModifiedEnd() != null) {
            example.and().andBetween("gmtModified", empCertificateQuery.getGmtModifiedStart(),
                    empCertificateQuery.getGmtModifiedEnd());
        }
        if (empCertificateQuery.getModifiedUserId() != null) {
            example.and().andLike("modifiedUserId", "%" + empCertificateQuery.getModifiedUserId() + "%");
        }
        // 排序
        ExampleKit.setExampleOrder(example,empCertificateQuery.getOrders());
        return example;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public Integer deleteEmpCertificate(TokenUser tokenUser, String empCertificateId){
        return empCertificateDAO.deleteByPrimaryKey(empCertificateId);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void deleteByCompanyId(String companyId, TokenUser tokenUser) {
        Example example = new Example(EmpCertificateDO.class);
        example.and()
                .andEqualTo("companyId", companyId)
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId());
        // 逻辑删除
        List<EmpCertificateDO> list = empCertificateDAO.selectByExample(example);
        String[] ids = list.stream()
                .map(BaseDO::getId).toArray(String[]::new);
        deleteByIds(tokenUser, ids);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void publishEmpCertificateList(List<EmpCertificateDTO> empCertificateList, String companyId, String empId, TokenUser tokenUser) {
        // 删除某个员工所有的
        deleteByEmpId(empId, tokenUser);

        if (CollectionUtils.isEmpty(empCertificateList)) {
            return;
        }

        empCertificateList.forEach(
                empCertificateDTO -> {
                    empCertificateDTO.setCompanyId(companyId);
                    empCertificateDTO.setEmpId(empId);
                    // 新增
                    EmpCertificateAddDTO empCertificateAddDTO = empCertificateDTO.to(EmpCertificateAddDTO.class);
                    save(empCertificateAddDTO, tokenUser);
                }
        );
    }

    @Override
    public List<EmpCertificateDO> listByEmpId(String empId, String siteId) {
        Example example = new Example(EmpCertificateDO.class);
        example.and()
                .andEqualTo("empId", empId)
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        return empCertificateDAO.selectByExample(example);
    }

    /**
     * 删除某个员工所有的
     *
     * @param empId     员工id
     * @param tokenUser 当前用户
     */
    private void deleteByEmpId(String empId, TokenUser tokenUser) {
        // 逻辑删除
        List<EmpCertificateDO> list = listByEmpId(empId, tokenUser.getSiteId());
        String[] ids = list.stream()
                .map(BaseDO::getId).toArray(String[]::new);
        deleteByIds(tokenUser, ids);
    }
}




